package com.pearl.camunda.study01.controller;

import com.pearl.camunda.study01.common.R;
import com.pearl.camunda.study01.vo.ProcessInstanceVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.camunda.bpm.engine.IdentityService;
import org.camunda.bpm.engine.RepositoryService;
import org.camunda.bpm.engine.RuntimeService;
import org.camunda.bpm.engine.impl.persistence.entity.ProcessInstanceWithVariablesImpl;
import org.camunda.bpm.engine.repository.Deployment;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.camunda.bpm.engine.runtime.ProcessInstanceQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;

/**
 * @author TD
 * @version 1.0
 * @date 2023/7/31
 */
@RequestMapping("/runtime")
@RestController
@Tag(name = "运行服务")
public class RuntimeController {

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private IdentityService identityService;

    @PostMapping("/startProcessInstanceByKey")
    @Operation(summary = "通过流程定义KEY启动流程")
    public R<String> startProcessInstanceByKey(String processDefinitionKey, String businessKey, String caseInstanceId, Map<String, Object> variables) {
        identityService.setAuthenticatedUserId("9527");
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processDefinitionKey, businessKey, caseInstanceId, variables);
        identityService.clearAuthentication();
        return R.success(processInstance.getProcessInstanceId());
    }

    @PostMapping("/startProcessInstanceById")
    @Operation(summary = "通过流程定义ID启动流程")
    public R<String> startProcessInstanceById(String processDefinitionId, String businessKey, String caseInstanceId, Map<String, Object> variables) {
        ProcessInstance processInstance = runtimeService.startProcessInstanceById(processDefinitionId, businessKey, caseInstanceId, variables);
        return R.success(processInstance.getProcessInstanceId());
    }

    @PostMapping("/createProcessInstanceQuery")
    @Operation(summary = "根据业务键和流程定义KEY查询实例")
    public R<String> startProcessInstanceById(@RequestParam String businessKey, String processDefinitionKey) {
        ProcessInstanceQuery query = runtimeService.createProcessInstanceQuery();
        ProcessInstance processInstance = query.processInstanceBusinessKey(businessKey)
                .processDefinitionKey(processDefinitionKey)
                .singleResult();
        return R.success(processInstance.getProcessInstanceId());
    }
}
